package com.lzy.cloud.search.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lzy.cloud.search.client.entity.EsQuery;
import com.lzy.cloud.search.client.service.SearchService;
import com.lzy.cloud.search.client.util.EsClient;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 搜索查询，返回查询匹配的结果，搜索一个index / type 或者多个index / type
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private EsClient client;

    public SearchResponse prepareSearch(EsQuery esQuery)   {
        SearchResponse response = client.getConnection().prepareSearch("twitter")//可以是多个index
                .setTypes("tweet")//可以是多个类型
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termQuery("user", "kimchy"))                 // Query 查询条件
//                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter 过滤
                .setFrom(0).setSize(60).setExplain(true)
                .get();

        //打印
        SearchHit[] searchHits = response.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            System.out.println(JSON.toJSONString(searchHit.getSourceAsString(), SerializerFeature.PrettyFormat));
        }
        return response;
    }


}
